package com.atguigu.flink.chapter07.state;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/17 12:11
 */
public class Flink09_Kafak_Flink_Kafka {
    public static void main(String[] args) throws Exception {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
    
        Properties sourceProps = new Properties();
        sourceProps.setProperty("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092");
        sourceProps.setProperty("group.id", "Flink09_Kafak_Flink_Kafka1");
        sourceProps.setProperty("auto.offset.reset", "latest");
        sourceProps.setProperty("isolation.level", "read_committed"); // 防止读到别人未提交的数据
        
    
    
        Properties sinkProps = new Properties();
        sinkProps.setProperty("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092");
        sinkProps.setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "");
        
        
        
    
        Configuration conf = new Configuration();
        conf.setInteger("reset.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env.setStateBackend(new FsStateBackend("hdfs://hadoop162:8020/flink/checkpoints/rocksdb"));
    
        env.enableCheckpointing(1000);
    
        // 高级选项：
        // 设置模式为精确一次 (这是默认值)
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
    
        // 确认 checkpoints 之间的时间会进行 500 ms
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
    
        // Checkpoint 必须在一分钟内完成，否则就会被抛弃
        env.getCheckpointConfig().setCheckpointTimeout(60000);
    
        // 同一时间只允许一个 checkpoint 进行
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
    
        // 开启在 job 中止后仍然保留的 externalized checkpoints
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
    
        SingleOutputStreamOperator<WaterSensor> stream = env
            .addSource(new FlinkKafkaConsumer<>("s1", new SimpleStringSchema(), sourceProps))
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            
            })
            .keyBy(WaterSensor::getId)
            .sum("vc");
        
        stream
            .addSink(new FlinkKafkaProducer<WaterSensor>(
                "s2",
                new KafkaSerializationSchema<WaterSensor>() {
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(WaterSensor element,
                                                                    @Nullable Long timestamp) {
                        return new ProducerRecord<>("s2", element.toString().getBytes(StandardCharsets.UTF_8));
                    }
                },
                sinkProps,
                FlinkKafkaProducer.Semantic.EXACTLY_ONCE));
        
        stream.addSink(new SinkFunction<WaterSensor>() {
            @Override
            public void invoke(WaterSensor value, Context context) throws Exception {
                //throw new RuntimeException("异常....");
            }
        });
        
        env.execute();
    
    }
}
/*
kafka服务器: 事务开始和结束时间不能超过15分钟
flink的生产者: 默认设置的事务的超时时间是1小时
 */